package com.woniuxy.shirospring.realm;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @author linke
 * @version 1.0
 * @className: MyRealm
 * @description: spring boot 整合realm
 * @date 2021/11/20 9:58
 */
public class UserRealm extends AuthorizingRealm {
    /**
     * 返回授权信息
     * @param principals 主要获取的权限信息
     * @return 具体权限信息
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("================doGetAuthorizationInfo");
        //去数据库的权限表查询当前用户的所有权限,获取当前用户
        Object primaryPrincipal = principals.getPrimaryPrincipal();
        System.out.println("================查询指定用户的所有权限:"+primaryPrincipal);
        Collection<String> permissions=new ArrayList<String>();
        //模拟从数据库中查询到的权限
        permissions.add("user:add");
        permissions.add("user:delete");
        SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
        //将查询出来的权限信息 添加进 授权
        authorizationInfo.addStringPermissions(permissions);
        //返回 授权信息
        return authorizationInfo;
    }

    /**
     * 返回认证信息
     *  密码加密
     * @param token 认证凭证信息
     * @return authenticationInfo 认证信息
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)  {
        System.out.println("doGetAuthenticationInfo");
        //token获取用户,去数据库查询
        Object principal = token.getPrincipal();
        //将查出来的用户凭证用户 比较
        if(!"a".equals(principal)){
            System.out.println(principal);
            return null;
        }
        System.out.println(principal);
        //获取凭证信息 要比较的密码
        Object credentials="567aedb9dc36acc7fdc8f08c7a51133a";
        ByteSource salt=ByteSource.Util.bytes("x");

        System.out.println(salt);
        AuthenticationInfo authenticationInfo=
                new SimpleAuthenticationInfo(principal,credentials,salt,this.getName());
        return authenticationInfo;
    }
}
